<template>
  <div>
    <el-dialog :title="title" :fullscreen=true :close-on-click-modal="false" :visible.sync="visible" @close="OnClose">
      <el-row :gutter="10">
        <el-col :span="15">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-map-panel">
            <PointAddList ref="pointAddList" :floorId='inputForm.floor.id' type="vr" url='/smis/vr/jfVrList/list'
              nameKey='name' @onMapClick="onMapClick" @onDataClick="onDataClick" @onLoadComplete="onLoadComplete" @dbClick="doSubmit()"></PointAddList>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-data-panel">
            <div class="uni-flex" style="justify-content: space-between;" @keydown="keydown">
              <div class="uni-camera-code" v-if="inputForm.cameraCode != ''">
                当前{{inputForm.cameraCode}}号相机<br/>
                <span style="color: #00ff00; font-weight: bolder;" v-if="inputForm.cameraCode === '1'">绿色</span>
                <span style="color: #ff0000; font-weight: bolder;" v-else-if="inputForm.cameraCode === '2'">红色</span>
              </div>
              <el-button type="text" v-if="hasPermission('smis:system')"  @click="doRecordSubmit()" v-noMoreClick>上传记录</el-button>
            </div>
            <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
              :disabled="method==='view'" label-width="120px">
              <el-row :gutter="15">
                <!-- <el-col :span="24">
                  <el-form-item label="名称" prop="name" :rules="[
                       ]">
                    <el-input v-model="inputForm.name" placeholder="请填写名称"></el-input>
                  </el-form-item>
                </el-col> -->
                <el-col :span="22">
                    <el-form-item label="照片名称" prop="name"
                        :rules="[
                          {required: true, message:'name不能为空', trigger:'blur'}
                         ]">
                      <el-input v-model="inputForm.name" placeholder="请填写名称"     ></el-input>
                      <el-checkbox v-model="autoUp" style="position: absolute; right: 5px; ">自增</el-checkbox>
                   </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="x轴" prop="x" :rules="[
                        {required: true, message:'x轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.x" placeholder="请填写x轴"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="y轴" prop="y" :rules="[
                        {required: true, message:'y轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.y" placeholder="请填写y轴"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-for="(item, index) in files" :key='index'>
                  <el-form-item :label="item.label" :prop="item.value" :rules="[
                        ]">
                    <vr-upload-ext :limit="1" :accept="item.format" :fileType="item.fileType" :width="item.width"
                      :height="item.height" :outputSize="0.7" outputType="jpeg" :allowScale="false"
                      :maxImageSize="10485760" v-model="inputForm.file[item.value]">
                    </vr-upload-ext>
                  </el-form-item>
                  <div></div>
                </el-col>
              </el-row>
            </el-form>
            <el-button type="primary" @click="doSubmit()" v-noMoreClick>添加(双击选中位置并提交)</el-button>
            <el-button type="info" style="margin-left: 50px; margin-bottom: 10px;" v-if="hasPermission('smis:system')" @click="doOfflineRecord()" v-noMoreClick>离线记录</el-button>
            <div class="uni-notice" v-if="hasPermission('smis:system')">网络不好环境，可先离线记录数据，待网络通畅后上传至服务器</div>
            <div class="uni-addlist-delete" v-if="selectItem.id !== ''">
              <div>当前选中了{{selectItem.name}}</div>
              <div style="color: #096DD9;" v-if="selectItem.img !== ''" @click="previewVr(selectItem.img)">预览VR图</div>
              <el-button type="danger" size="small" @click="doDelete()" v-noMoreClick>删除</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
    <vr-preview ref="vrPreview"></vr-preview>
  </div>
</template>

<script>
  import PointAddList from '@/components/jfMap/pointAddList.vue'
  import VrUploadExt from '@/components/vrUploadExt/index.vue'
  import VrPreview from '@/components/jfMap/vrPreview.vue'
  export default {
    data() {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        autoUp: false,
        selectItem: {
          id: '',
          name: '',
          img: ''
        },
        files: [{
          label: '全景图',
          value: 'img',
          format: '.JPG,.JPEG',
          fileType: '2',
          // width: '8000',
          // height: '4000'
          width: '2048',
          height: '1024'
        }],
        inputForm: {
          id: '',
          cameraCode: '',
          floor: {
            id: ''
          },
          name: 'R001',
          x: '',
          y: '',
          angle: '',
          file: {},
          filesAll: ''
        }
      }
    },
    components: {
      PointAddList,
      VrUploadExt,
      VrPreview
    },
    computed: {
      contentViewHeight() {
        let height = this.$store.state.common.documentClientHeight - 152
        return {
          height: height + 'px'
        }
      }
    },
    methods: {
      init(method, id, floorId) {
        this.$prompt('请输入相机编码', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          inputErrorMessage: '请输入相机编码，1号相机1'
        }).then(({
          value
        }) => {
          this.inputForm.cameraCode = value || ''
          this.method = method
          this.inputForm.id = id
          this.title = `批量添加`
          this.visible = true
          this.loading = false
          this.$nextTick(() => {
            this.inputForm.floor.id = floorId
            this.resetFields()
            this.$refs.pointAddList.resize();
            this.$refs.pointAddList.showFloor(floorId)
          })
        }).catch(() => {

        });
      },
      keydown(e) {
        console.log(e)
      },
      resetFields() {
        this.inputForm.id = ''
        this.inputForm.name = this.autoUp ? this.getAutoUpNumber( this.inputForm.name) : 'R001'
        this.inputForm.file = {}
        this.inputForm.filesAll = ''
        this.inputForm.x = ''
        this.inputForm.y = ''
		this.inputForm.z = ''
        this.inputForm.angle = 0
      },
      previewVr (imgUrl) {
        this.$refs.vrPreview.showVr(imgUrl)
      },
      getAutoUpNumber(code)  {
        if(!code || code === "") {
          return ""
        }
        var list = code.split("")
        var numCode = ''
        for(var i= list.length-1; i>=0; i--) {
        	var isnum = /^\d+$/.test(list[i]);
        	if(isnum) {
        		numCode = list[i]+numCode
        	} else {
        		break
        	}
        }
        if(numCode === '') {
        	return code
        }
        var prefix = code.substr(0, code.length - numCode.length)
        var newCode = (parseInt(numCode)+1)+''
        for(var len =newCode.length, i=0; i<numCode.length-len; i++) {
        	newCode = '0'+newCode
        }
        return prefix+newCode
      },
      // 表单提交
      doSubmit(callback) {
        this.inputForm.filesAll = JSON.stringify(this.inputForm.file)
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/smis/vr/jfVrList/save`,
              method: 'post',
              data: this.inputForm
            }).then(({
              data
            }) => {
              if (data && data.success) {
                this.$message.success(data.msg)
                this.$refs.pointAddList.refreshList()
                this.resetFields()
                callback && callback()
              }
              this.loading = false
            })
          }
        })
      },
      getRecordList() {
        var recordStr = localStorage.getItem("vrRecordList");
        if(recordStr && recordStr.length > 4) {
          return JSON.parse(recordStr);
        }
        return []
      },
      // 上传保存离线记录
      doRecordSubmit() {
        var recordList = this.getRecordList();
        if(recordList.length > 0) {
          this.inputForm = recordList.pop();
          this.$nextTick(()=>{
            this.doSubmit(()=>{
              this.$refs.pointAddList.removeMarkPoint(this.inputForm.name)
              localStorage.setItem("vrRecordList", JSON.stringify(recordList))
              this.doRecordSubmit();
            });
          })
        }
      },
      // 离线记录
      doOfflineRecord() {
        this.inputForm.filesAll = JSON.stringify(this.inputForm.file)
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            var recordList = this.getRecordList();
            recordList.push(this.inputForm);
            localStorage.setItem("vrRecordList", JSON.stringify(recordList))
            this.$message.success("已存储至缓存，当前缓存记录数："+recordList.length+"条")
            this.$refs.pointAddList.addMarkPoint(this.inputForm.name, this.inputForm.name, this.inputForm.floor.id, this.inputForm.x, this.inputForm.y, this.inputForm.z|| 0)
            this.resetFields()
          }
        })
      },
      onLoadComplete() {
        setTimeout(()=>{
          var recordList = this.getRecordList();
          for(var i=0; i<recordList.length; i++) {
            this.$refs.pointAddList.addMarkPoint(recordList[i].name, recordList[i].name, recordList[i].floor.id, recordList[i].x, recordList[i].y, recordList[i].z|| 0)
          }
        },100)
      },
      doDelete() {
        // 检查缓存是否存在，存在则删缓存的
        var recordList = this.getRecordList();
        for(var i=0; i<recordList.length; i++) {
          if(recordList[i].name === this.selectItem.id) {
            this.$message.success("已删除对应缓存记录")
            this.$refs.pointAddList.removeMarkPoint(this.selectItem.id);
            this.selectItem = {
              id: '',
              name: ''
            }
            recordList.splice(i,1);
            localStorage.setItem("vrRecordList", JSON.stringify(recordList))
            return;
          }
        }
        this.loading = true
        this.$http({
          url: '/smis/vr/jfVrList/delete',
          method: 'delete',
          params: {
            'ids': this.selectItem.id
          }
        }).then(({
          data
        }) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.$refs.pointAddList.refreshList()
            this.selectItem = {
              id: '',
              name: ''
            }
          }
          this.loading = false
        })
      },
      onMapClick(e) {
        this.inputForm.x = e.x
        this.inputForm.y = e.y
		this.inputForm.z = e.z
      },
      onDataClick(e) {
        // console.log(e)
        var imgUrl = ""
        if(e.userData && e.userData.filesAll) {
          var filesAll = JSON.parse(e.userData.filesAll)
          imgUrl = filesAll.img;
        }
        this.selectItem = e
        this.selectItem.img = imgUrl
      },
      OnClose() {
        this.$emit('refreshDataList')
      }
    }
  }
</script>
<style>
  .uni-camera-code {
    padding: 12px;
  }
</style>
